package com.filetransfer.app.ui.dashboard

import android.app.Activity
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.ViewModel
import androidx.recyclerview.widget.RecyclerView
import com.filetransfer.api.ShareCollection
import com.filetransfer.api.ShareCollection.ShareResult
import com.filetransfer.api.ShareCollection.ShareResultToken
import com.filetransfer.app.R
import com.filetransfer.app.db.HistoryDatabaseHelper.History
import com.filetransfer.app.ui.upload.ShareResultDialog
import java.util.function.Consumer

class DashboardViewModel : ViewModel() {
}

class UploadHistoryAdapter(private val dataList: List<History>) :
    RecyclerView.Adapter<UploadHistoryAdapter.ViewHolder>() {
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val fileName: TextView = view.findViewById(R.id.tvFileName)
        val code: TextView = view.findViewById(R.id.tvCode)
        val status: TextView = view.findViewById(R.id.tvStatus)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_upload_history, parent, false) // 确保此处为正确布局文件
        return ViewHolder(view)
    }

    private fun getShareInfo(
        code: String,
        callback: Consumer<ShareResult>,
        onError: Consumer<Exception?>
    ) {
        Thread {
            try {
                val info = ShareCollection.getInfoByShareCode(code)
                callback.accept(info)
            } catch (e: Exception) {
                onError.accept(e)
            }
        }.start()
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = dataList[position]
        holder.fileName.text = Uri.parse(item.fileName).path?.split('/')?.last()
        holder.fileName.setOnClickListener {
            this.getShareInfo(item.code, {
                (holder.itemView.context as Activity).runOnUiThread {
                    val dialog = ShareResultDialog(
                        holder.itemView.context,
                        it,
                        {
                        }
                    )
                    dialog.show()
                }
            }, {
                it?.printStackTrace()
            })
        }
        holder.code.text = item.code
        holder.status.text = item.status
    }

    override fun getItemCount(): Int = dataList.size
}
